package com.pulanit.pangu.admin.web.controller.business;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PageResult;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PagingUtil;
import com.pulanit.pangu.admin.business.api.entity.*;
import com.pulanit.pangu.admin.business.api.param.ArticlePageIn;
import com.pulanit.pangu.admin.business.api.service.*;
import com.gitee.pulanos.pangu.framework.sdk.dto.Result;
import com.pulanit.pangu.admin.common.AppContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文稿 前端控制器
 * </p>
 *
 * @author 天鸣
 * @since 2024-02-20
 */
@RestController
@RequestMapping("/api/business/article")
public class ArticleController {

    @Value("${server.port}")
    private int serverPort;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IColumnEditService columnEditService;

    @Autowired
    private IFieldService fieldService;

    @Autowired
    private IArticleEditService articleEditService;

    @Autowired
    private IColumnService columnService;

    @Autowired
    private IArticleExpertService articleExpertService;

    /**
     * 文稿管理-列表
     */
    @GetMapping("/page")
    public Result<PageResult<Article>> list(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //条件
        wrapper.eq(Article::getArticleUserId, AppContext.getUserInfo().getId());
        wrapper.ne(Article::getArticleStatus, 5);
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.orderByDesc(Article::getSubmitDate);
        return getPageResult(page, wrapper);
    }

    /**
     * 已发布管理-列表
     */
    @GetMapping("/publishedPage")
    public Result<PageResult<Article>> publishedPage(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //条件
        wrapper.eq(Article::getArticleStatus, 2);
        wrapper.eq(Article::getPublishStatus, 1);
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.orderByDesc(Article::getPublishDate);
        return getPageResult(page, wrapper);
    }


    /**
     * 退稿建议管理-列表
     */
    @GetMapping("/advicePage")
    public Result<PageResult<Article>> advicePage(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //条件
        wrapper.eq(Article::getArticleUserId, AppContext.getUserInfo().getId());
        wrapper.in(Article::getArticleStatus, 4, 5);
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.orderByDesc(Article::getSubmitDate);
        return getPageResult(page, wrapper);
    }

    /**
     * 编辑-文稿列表
     */
    @GetMapping("/allotPage")
    public Result<PageResult<Article>> allotList(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //搜索编辑所属栏目id
        LambdaQueryWrapper<ColumnEdit> columnEditLambdaQueryWrapper = new LambdaQueryWrapper<>();
        columnEditLambdaQueryWrapper.eq(ColumnEdit::getEditUserId, AppContext.getUserInfo().getId());
        List<ColumnEdit> list = columnEditService.list(columnEditLambdaQueryWrapper);
        List<Long> columnIds = list.stream().map(ColumnEdit::getColumnId).collect(Collectors.toList());
        if (list.size() <= 0) {
            return Result.success(PagingUtil.transformPageResult(new Page<>(page.getCurrent(), page.getSize())));
        }

        //条件
        wrapper.in(Article::getColumnId, columnIds);
        wrapper.eq(Article::getArticleStatus, 1);
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.orderByAsc(Article::getSubmitDate);
        return getPageResult(page, wrapper);
    }

    /**
     * 编辑总结-文稿列表
     */
    @GetMapping("/advisePage")
    public Result<PageResult<Article>> advisePage(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<ArticleEdit> articleEditLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleEditLambdaQueryWrapper.eq(ArticleEdit::getEditUserId, AppContext.getUserInfo().getId());
        List<ArticleEdit> list = articleEditService.list(articleEditLambdaQueryWrapper);
        List<Long> articleIds = list.stream().map(ArticleEdit::getArticleId).collect(Collectors.toList());
        if (list.size() <= 0) {
            return Result.success(PagingUtil.transformPageResult(new Page<>(page.getCurrent(), page.getSize())));
        }
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Article::getId, articleIds);
        wrapper.in(Article::getArticleStatus, 3, 4, 5);
        return getPageResult(page, wrapper);
    }

    /**
     * 管理员-发布文稿列表
     */
    @GetMapping("/publishPage")
    public Result<PageResult<Article>> publishPage(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //条件
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.eq(ObjectUtil.isNotEmpty(articlePageIn.getPublishStatus()), Article::getPublishStatus, articlePageIn.getPublishStatus());
        wrapper.eq(Article::getArticleStatus, 2);
        wrapper.orderByDesc(Article::getPublishDate);
        return getPageResult(page, wrapper);
    }

    /**
     * 专家-文稿列表
     */
    @GetMapping("/checkPage")
    public Result<PageResult<Article>> checkPage(ArticlePageIn articlePageIn) {
        Page<Article> page = PagingUtil.createPage(articlePageIn);
        //搜索编辑所属栏目id
        LambdaQueryWrapper<ArticleExpert> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleExpert::getExpertUserId, AppContext.getUserInfo().getId())
                .eq(ArticleExpert::getRefuse, 1);
        List<ArticleExpert> list = articleExpertService.list(queryWrapper);
        List<Long> articleIds = list.stream().map(ArticleExpert::getArticleId).collect(Collectors.toList());
        if (list.size() <= 0) {
            return Result.success(PagingUtil.transformPageResult(new Page<>(page.getCurrent(), page.getSize())));
        }
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //条件
        wrapper.like(StrUtil.isNotEmpty(articlePageIn.getKeyword()), Article::getArticleTitle, articlePageIn.getKeyword());
        wrapper.in(Article::getId, articleIds);
        wrapper.orderByAsc(Article::getSubmitDate);

        Page<Article> resultPage = articleService.page(page, wrapper);
        resultPage.getRecords().forEach(item -> {
            //处理文件地址
            if (StrUtil.isNotBlank(item.getArticleFile())) {
                try {
                    InetAddress address = InetAddress.getLocalHost();
                    String localPrefix = "http://" + address.getHostAddress() + ":" + Convert.toStr(serverPort);
                    String downloadFile = localPrefix + item.getArticleFile();
                    item.setDownloadFile(downloadFile);
                } catch (UnknownHostException e) {
                    throw new RuntimeException(e);
                }
            }
            //领域名
            Field field = fieldService.getById(item.getFieldId());
            if (ObjectUtil.isNotEmpty(field)) {
                item.setFieldName(field.getFieldName());
            }
            //栏目名
            Column column = columnService.getById(item.getColumnId());
            if (ObjectUtil.isNotEmpty(column)) {
                item.setColumnName(column.getColumnName());
            }
            //是否通过审核
            LambdaQueryWrapper<ArticleExpert> expertLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expertLambdaQueryWrapper.eq(ArticleExpert::getArticleId, item.getId())
                    .eq(ArticleExpert::getExpertUserId, AppContext.getUserInfo().getId())
                    .last("limit 1");
            ArticleExpert articleExpert = articleExpertService.getOne(expertLambdaQueryWrapper);
            item.setCheckStatus(articleExpert.getCheckStatus());
        });
        return Result.success(PagingUtil.transformPageResult(resultPage));
    }

    /**
     * 获取列表
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<Article>> list() {
        List<Article> list = articleService.list();
        return Result.success(list);
    }

    /**
     * 获取详情
     *
     * @return
     */
    @GetMapping("/detail")
    public Result<Article> detail(@RequestParam("id") Long id) {
        Assert.notNull(id, "ID 不能为空");
        Article article = articleService.getById(id);
        //处理文件地址
        if (StrUtil.isNotBlank(article.getArticleFile())) {
            try {
                InetAddress address = InetAddress.getLocalHost();
                String localPrefix = "http://" + address.getHostAddress() + ":" + Convert.toStr(serverPort);
                String downloadFile = localPrefix + article.getArticleFile();
                article.setDownloadFile(downloadFile);
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        }
        return Result.success(article);
    }

    /**
     * 提交
     *
     * @return
     */
    @PostMapping("/submit")
    public Result<Void> submit(@RequestParam("id") Long id) {
        Assert.notNull(id, "人员 ID 不能为空");
        Article article1 = articleService.getById(id);
        if (ObjectUtil.isEmpty(article1)) {
            return Result.fail("提交失败");
        }
        //退稿文件需要修改后提交
        if (article1.getArticleStatus() == 3) {
            return Result.fail("退稿文件请修改后提交");
        }
        Article article = new Article();
        article.setId(id);
        article.setArticleStatus(1);
        article.setSubmitDate(DateTime.now().toLocalDateTime());
        articleService.updateById(article);
        return Result.success();
    }

    /**
     * 发布或者取消发布
     *
     * @return
     */
    @PostMapping("/publish")
    public Result<Void> publish(@RequestParam("id") Long id, @RequestParam("publishStatus") Integer publishStatus) {
        Assert.notNull(id, "人员 ID 不能为空");
        //退稿文件需要修改后提交
        Article article = new Article();
        article.setId(id);
        article.setPublishStatus(publishStatus);
        article.setPublishDate(DateTime.now().toLocalDateTime());
        articleService.updateById(article);
        return Result.success();
    }


    /**
     * 审核文稿
     *
     * @return
     */
    @PostMapping("/check")
    public Result<Void> check(@RequestParam("id") Long id,
                              @RequestParam("articleStatus") Integer articleStatus,
                              @RequestParam(value = "callbackAdvise", required = false) String callbackAdvise) {
        Assert.notNull(id, "人员 ID 不能为空");
        Article article1 = articleService.getById(id);
        Article article = new Article();
        Integer checkNum = article1.getCheckNum() + 1;
        if (articleStatus == 2) {
            Integer successNum = article1.getSuccessNum() + 1;
            if (checkNum >= 3 && checkNum.equals(successNum)) {
                article.setArticleStatus(2);
            }
            article.setSuccessNum(successNum);

            LambdaUpdateWrapper<ArticleExpert> LambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper.set(ArticleExpert::getCheckStatus, 1)
                    .eq(ArticleExpert::getArticleId, id)
                    .eq(ArticleExpert::getExpertUserId, AppContext.getUserInfo().getId());
            articleExpertService.update(LambdaUpdateWrapper);
        } else {
            article.setArticleStatus(3);
            LambdaUpdateWrapper<ArticleExpert> LambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper.set(ArticleExpert::getCheckStatus, 2)
                    .set(StrUtil.isNotEmpty(callbackAdvise), ArticleExpert::getCallbackAdvise, callbackAdvise)
                    .eq(ArticleExpert::getArticleId, id)
                    .eq(ArticleExpert::getExpertUserId, AppContext.getUserInfo().getId());
            articleExpertService.update(LambdaUpdateWrapper);
        }

        article.setCheckNum(checkNum);
        article.setId(id);
        articleService.updateById(article);
        return Result.success();
    }

    /**
     * 保存
     *
     * @param article
     * @return
     */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Article article) {
        article.setArticleStatus(0);
        article.setPublishStatus(0);
        article.setArticleUserId(AppContext.getUserInfo().getId());
        articleService.save(article);
        return Result.success();
    }

    /**
     * 修改
     *
     * @param article
     * @return
     */
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Article article) {
        if (article.getArticleStatus() == 4) {
            Article article1 = new Article();
            article1.setArticleTitle(article.getArticleTitle());
            article1.setArticleUserId(AppContext.getUserInfo().getId());
            article1.setFieldId(article.getFieldId());
            article1.setColumnId(article.getColumnId());
            article1.setArticleFile(article.getArticleFile());
            article1.setKeyword(article.getKeyword());
            article1.setAbstractZn(article.getAbstractZn());
            article1.setAbstractEn(article.getAbstractEn());
            article1.setCheckNum(0);
            article1.setSuccessNum(0);
            article1.setArticleStatus(0);
            article1.setPublishStatus(0);
            articleService.save(article1);
            article.setArticleStatus(5);
        }
        articleService.updateById(article);
        return Result.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result<Void> delete(@RequestParam("id") Long id) {
        Assert.notNull(id, "人员 ID 不能为空");
        articleService.removeById(id);
        return Result.success();
    }

    /**
     * 退稿建议
     *
     * @return
     */
    @PostMapping("/callback")
    public Result<Void> callback(@RequestParam("id") Long articleId,
                                 @RequestParam("callbackAdvise") String callbackAdvise) {
        Assert.notNull(articleId, "文稿 ID 不能为空");

        LambdaUpdateWrapper<ArticleEdit> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(ArticleEdit::getCallbackAdvise, callbackAdvise)
                .eq(ArticleEdit::getArticleId, articleId)
                .eq(ArticleEdit::getEditUserId, AppContext.getUserInfo().getId());
        articleEditService.update(wrapper);
        Article article = new Article();
        article.setId(articleId);
        article.setArticleStatus(4);
        articleService.updateById(article);
        return Result.success();
    }

    /**
     * 查看退稿建议
     *
     * @return
     */
    @GetMapping("/callbackDetail")
    public Result<ArticleEdit> callbackDetail(@RequestParam("id") Long articleId) {
        Assert.notNull(articleId, "文稿 ID 不能为空");
        LambdaQueryWrapper<ArticleEdit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleEdit::getArticleId, articleId);
        return Result.success(articleEditService.getOne(wrapper));
    }

    /**
     * 批量删除
     */
    @PostMapping("/batchDelete")
    public Result<Void> batchDelete(@RequestParam List<Long> ids) {
        Assert.notEmpty(ids, "人员 ID 不能为空");
        articleService.removeBatchByIds(ids);
        return Result.success();
    }

    private Result<PageResult<Article>> getPageResult(Page<Article> page, LambdaQueryWrapper<Article> wrapper) {
        Page<Article> resultPage = articleService.page(page, wrapper);
        resultPage.getRecords().forEach(item -> {
            //处理文件地址
            if (StrUtil.isNotBlank(item.getArticleFile())) {
                try {
                    InetAddress address = InetAddress.getLocalHost();
                    String localPrefix = "http://" + address.getHostAddress() + ":" + Convert.toStr(serverPort);
                    String downloadFile = localPrefix + item.getArticleFile();
                    item.setDownloadFile(downloadFile);
                } catch (UnknownHostException e) {
                    throw new RuntimeException(e);
                }
            }
            //领域名
            Field field = fieldService.getById(item.getFieldId());
            if (ObjectUtil.isNotEmpty(field)) {
                item.setFieldName(field.getFieldName());
            }
            //栏目名
            Column column = columnService.getById(item.getColumnId());
            if (ObjectUtil.isNotEmpty(column)) {
                item.setColumnName(column.getColumnName());
            }
        });
        return Result.success(PagingUtil.transformPageResult(resultPage));
    }
}
